import 'package:flutter/material.dart';
import 'package:flutterapp2/util/image_util.dart';

typedef RatingBuilder = Widget Function(bool selected);

/// 星级评分控件
class RatingBar extends StatefulWidget {
  static const DEFAULT_COUNT = 5;
  static const DEFAULT_SPACE = 1.0;
  static const DEFAULT_CLICK_ENABLE = false;

  final int count;
  final int selectedCount;
  final double space;

  // 是否允许反选，仅第一个有效
  final bool canDeselect;

  final RatingBuilder builder;
  final ValueChanged<int> onSelected;

  const RatingBar({
    Key key,
    this.count = DEFAULT_COUNT,
    this.selectedCount = 0,
    this.space = DEFAULT_SPACE,
    this.builder,
    this.onSelected,
    this.canDeselect = false,
  }) : super(key: key);

  @override
  _RatingBarState createState() => _RatingBarState();
}

class _RatingBarState extends State<RatingBar> {
  int currSelected;

  @override
  void initState() {
    super.initState();
    currSelected = widget.selectedCount;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: _getContent(),
    );
  }

  List<Widget> _getContent() {
    List<Widget> list = List();
    for (var i = 0; i < widget.count; i++) {
      var isSelected = i < currSelected;
      var rating = widget.builder != null ? widget.builder(isSelected) : _buildRating(isSelected);

      if (widget.onSelected != null) {
        list.add(GestureDetector(
          child: rating,
          onTap: () {
            // 反选第一个
            if (i == 0 && currSelected == 1 && widget.canDeselect) {
              currSelected = 0;
            } else {
              currSelected = i + 1;
            }
            widget.onSelected(currSelected);
            setState(() {});
          },
          behavior: HitTestBehavior.opaque,
        ));
      } else {
        list.add(rating);
      }

      if (i != widget.count - 1) {
        list.add(SizedBox(
          width: widget.space,
          height: 1,
        ));
      }
    }
    return list;
  }

  Widget _buildRating(bool selected) {
    return Image.asset(
      ImageUtil.getImagePath("icon_star"),
      width: 22,
      height: 22,
      color: selected ? Color(0xFFD5925B) : Color(0xFFCCCCCC),
    );
  }
}
